<template>
  <div class="tablecompbox">
    <div class="btn-list">
      <!-- 按钮列表 -->
      <div class="list-left">
        <el-button
          type="primary"
          round
          icon="el-icon-circle-plus-outline"
          size="small"
          @click="handleAddUser"
        >
          新增</el-button
        >
        <el-button
          type="primary"
          round
          icon="el-icon-delete"
          size="small"
          @click="handleAllDelete"
        >
          批量删除</el-button
        >
      </div>
      <div class="list-right">
        <el-button
          icon="el-icon-refresh"
          circle
          @click="refreshTable"
        ></el-button>
        <el-button icon="el-icon-download" circle></el-button>
      </div>
    </div>
    <!-- 表格列表 -->
    <div class="tablelist">
      <el-table
        ref="multipleTable"
        v-loading="isLoading"
        :data="showTableData"
        style="width: 100%"
        :header-cell-style="{ background: '#e1e4e5', color: '#80878f' }"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"> </el-table-column>
        <el-table-column prop="nickname" label="用户名称" />
        <el-table-column prop="depa" label="部门" />
        <el-table-column prop="role" label="角色" />
        <el-table-column prop="email" label="邮箱" />
        <el-table-column prop="phone" label="手机号" />
        <el-table-column prop="mtime" label="创建时间" />
        <el-table-column label="操作">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.$index, scope.row)"
              >编辑</el-button
            >
            <el-button
              class="delete-btn"
              size="small"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)"
              :loading="scope.row.id === deleteRow.id"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="page">
      <el-pagination
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-size="pageSize"
        :page-sizes="[5, 10, 15, 20]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalPagination"
      />
    </div>
    <FormDialog
      :toggle="userDialog"
      :title="title"
      :userData="userData"
      @closeDialog="handleCloseDialog"
      @updateTable="handleUpdate"
    />
  </div>
</template>

<script>
import { userList } from "@/mockApi/homepage/MockUserList";
import { mapGetters } from "vuex";
// dialog组件
import FormDialog from "@/views/homepage/workbench/FormDialog.vue";
export default {
  name: "TableComp",
  components: {
    FormDialog,
  },
  computed: {
    // 获取vuex中表单数据
    ...mapGetters("searchForm", ["changeFormData"]),
    showTableData() {
      console.log(this.tableData, "拿table的数据", this.changeFormData?.name);

      // 通过getter的数据对列表渲染
      return this.tableData
        .filter((row) => row.nickname.includes(this.changeFormData?.name))
        .filter((row) => row.depa.includes(this.changeFormData?.depa))
        .filter((row) => row.phone.includes(this.changeFormData?.phone))
        .filter((row) => row?.mtime?.includes(this.changeFormData?.date1))
        .filter((row) => row?.mtime?.includes(this.changeFormData?.date2))
        .slice(
          (this.currentPage - 1) * this.pageSize,
          this.currentPage * this.pageSize
        );
    },
    totalPagination() {
      // 总条数设置
      const isSearch =
        this.changeFormData?.name.length > 0 ||
        this.changeFormData?.depa.length > 0 ||
        this.changeFormData?.phone.length > 0 ||
        this.changeFormData?.date1.length > 0 ||
        this.changeFormData?.date2.length > 0;

      // 用户进行「姓名的模糊搜索」
      if (isSearch) {
        return this.showTableData.length;
      } else {
        // 用户不进行「姓名的模糊搜索」
        return this.tableData.length;
      }
    },
  },
  data() {
    return {
      tableData: [],
      isLoading: false,
      deletedRow: {}, // 表示 要被删除的行
      searchName: "",
      currentPage: 1,
      pageSize: 5,
      multipleSelection: [], //单选存放
      formData: "",
      deleteRow: {}, // 表示 要被删除的行
      userDialog: false, // 为 true ，即 UserDialog 显示
      title: "", // dialog标题
      userData: {}, // 点击编辑，所在行的数据
    };
  },

  methods: {
    // 批量删除
    handleAllDelete() {
      this.multipleSelection.forEach((item) => {
        userList.delete2(item.userId).then((res) => {
          this.$message.success(`删除 - 成功`);
          if (res.status === "success") {
            setTimeout(() => {
              this.refreshTable();
            }, 1000);
          }
        });
      });
    },
    // 定义当前页
    handleCurrentChange(val) {
      this.currentPage = val;
    },
    // 点击单选按钮，val是所在行数据
    handleSelectionChange(val) {
      console.log(val);
      this.multipleSelection = val;
    },
    // 编辑按钮业务逻辑
    handleEdit(i, row) {
      this.userDialog = true; // 显示 dialog
      this.title = "编辑用户";
      this.userData = row;
    },
    // 关闭dialog，toggle为true
    handleCloseDialog() {
      this.userDialog = false;
      this.userData = {};
    },
    // 编辑后更新table
    handleUpdate() {
      this.refreshTable();
    },
    // 新增按钮业务逻辑
    handleAddUser() {
      this.userDialog = true; // 显示 dialog
      // this.title = "新增用户";
    },

    // 删除业务逻辑
    handleDelete(i, row) {
      this.deleteRow = row;
      userList
        .delete(row.id)
        .then((res) => {
          if (res.status === "success") {
            this.$message.success(`删除此人 - ${row.nickname} 成功`);

            setTimeout(() => {
              this.refreshTable();
            }, 1000);
          }
        })
        .finally(() => {
          this.deleteRow = {};
        });
    },
    // 执行本函数，即拉取 最新的 table 数据，后 更新 table
    refreshTable() {
      this.isLoading = true;
      userList
        .getAll()
        .then((res) => {
          this.tableData = res;
        })
        .catch((err) => {
          this.$message.error(`拉取 table 接口报错:${err}`);
        })
        .finally(() => {
          this.isLoading = false;
        });
    },
  },
  mounted() {
    this.refreshTable();
    // 获取vuex中state的数据
  },
  // watch: {
  //   formState() {
  //     console.log("改变state");
  //   },
  //   changeFormData() {
  //     console.log("改变getter");
  //   },
  // },
};
</script>

<style scoped lang="scss">
.tablecompbox {
  width: 100%;
  height: 500px;
  background: #fff;
  margin-top: 10px;
  border-radius: 8px;
  padding: 15px;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  .btn-list {
    display: flex;
    justify-content: space-between;
    margin-bottom: 10px;

    .el-button {
      border: none;
    }
  }
  .tablelist {
    height: 400px;
    flex: 1;
  }
  .page {
    height: 60px;
    // background: pink;
    display: flex;
    justify-content: center;
    align-items: center;
  }
}
</style>
